﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Common;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.dbEntity;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Enum;
using XF.Meeting.Entity.Query;
using XF.Meeting.Entity.View;
using XF.Meeting.IDal;
using XF.Sugar.IService;

namespace XF.Meeting.Service
{
    public class GroupInfoService : BaseService, IGroupInfoService
    {
        private IGroupDal dal = null;

        public GroupInfoService(string Operator, string OperaIP)
        {
            this.Operator = Operator;
            this.OperaIP = OperaIP;
            if (dal == null)
            {
                lock (this.OperaIP)
                {
                    if (dal == null)
                    {
                        dal = DalFactory.DalFactory.GetGroupDaL();
                    }
                }
            }
        }

        private UEntity.LogEntity.ELogRecordEntity LogEntity = new UEntity.LogEntity.ELogRecordEntity();

        /// <summary>
        /// 新增群组
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<(bool, string)> AddGroup(GroupInfo entity)
        {
            string strError = "";
            bool bResult = true;
            LogEntity.Module = "XF.Meeting.Service.MeetingService.AddGroup";
            LogEntity.OperateObject = "AddGroup";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = EntityToString.GetEntityToString<GroupInfo>(entity);
            try
            {
                var list = await GetGroupOne(new GroupQuery()
                {
                    Key = "",
                    pageIndex = 1,
                    pageSize = 10000,
                });
                foreach (var item in list.List)
                {
                    if (item.GroupName.Trim() == entity.GroupName.Trim())
                    {
                        bResult = false;
                        strError = "存在同名群组名称";
                        return (bResult, strError);
                    }
                }

                bResult = await dal.AddGroup(entity, out strError);
                if (!bResult)
                {
                    LogEntity.OperateResult = "Fail";
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                LogEntity.OperateResult = "Fail";
                strError = string.Format("AddGroup Exception:{0}", ex.ToString());

            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return (bResult, strError);
        }

        /// <summary>
        /// 删除群组
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<(bool, string)> DeleteGroup(GroupInfo entity)
        {
            string strError = "";
            bool bResult = true;
            LogEntity.Module = "XF.Meeting.Service.MeetingService.DeleteGroup";
            LogEntity.OperateObject = "DeleteGroup";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = EntityToString.GetEntityToString<GroupInfo>(entity);
            try
            {
               
                bResult = await dal.DeleteGroup(entity, out strError);
                if (!bResult)
                {
                    LogEntity.OperateResult = "Fail";
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                LogEntity.OperateResult = "Fail";
                strError = string.Format("DeleteGroup Exception:{0}", ex.ToString());

            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return (bResult, strError);
        }

        /// <summary>
        /// 修改群组
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<(bool, string)> UpdateGroup(GroupInfo entity)
        {
            string strError = "";
            bool bResult = true;
            LogEntity.Module = "XF.Meeting.Service.MeetingService.UpdateGroup";
            LogEntity.OperateObject = "UpdateGroup";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = EntityToString.GetEntityToString<GroupInfo>(entity);
            try
            {
                var list = await GetGroupOne(new GroupQuery()
                {
                    Key = "",
                    pageIndex = 1,
                    pageSize = 10000,
                });
                foreach (var item in list.List)
                {
                    if (item.GroupName.Trim() == entity.GroupName.Trim())
                    {
                        bResult = false;
                        strError = "存在同名群组名称";
                        return (bResult, strError);
                    }
                }
                bResult = await dal.UpdateGroup(entity, out strError);
                if (!bResult)
                {
                    LogEntity.OperateResult = "Fail";
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                LogEntity.OperateResult = "Fail";
                strError = string.Format("UpdateGroup Exception:{0}", ex.ToString());

            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return (bResult, strError);
        }

        /// <summary>
        /// 群组添加用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<(bool, string)> AddGroupUser(GroupInfo entity)
        {
            string strError = "";
            bool bResult = true;
            LogEntity.Module = "XF.Meeting.Service.MeetingService.AddGroupUser";
            LogEntity.OperateObject = "AddGroupUser";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = EntityToString.GetEntityToString<GroupInfo>(entity);
            try
            {

                bResult = await dal.AddGroupUser(entity, out strError);
                if (!bResult)
                {
                    LogEntity.OperateResult = "Fail";
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                LogEntity.OperateResult = "Fail";
                strError = string.Format("AddGroupUser Exception:{0}", ex.ToString());

            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return (bResult, strError);
        }

        /// <summary>
        /// 群组修改删除用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<(bool, string)> UpdateGroupUser(GroupInfo entity)
        {
            string strError = "";
            bool bResult = true;
            LogEntity.Module = "XF.Meeting.Service.MeetingService.UpdateGroupUser";
            LogEntity.OperateObject = "UpdateGroupUser";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = EntityToString.GetEntityToString<GroupInfo>(entity);
            try
            {

                bResult = await dal.UpdateGroupUser(entity, out strError);
                if (!bResult)
                {
                    LogEntity.OperateResult = "Fail";
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                LogEntity.OperateResult = "Fail";
                strError = string.Format("UpdateGroupUser Exception:{0}", ex.ToString());

            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return (bResult, strError);
        }

        /// <summary>
        /// 获取群组根节点信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageList<GroupInfoDTO>> GetGroupOne(GroupQuery query)
        {
            PageList<GroupInfoDTO> list = new PageList<GroupInfoDTO>();
            
            string strError = "";
            LogEntity.Module = "XF.Meeting.Service.MeetingService.GetGroupOne";
            LogEntity.OperateObject = "GetGroupOne";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {
                var res = await dal.GetGroupOne(query,out strError);

                if (strError == "")
                {
                    list.List = TableToList.ToList<GroupInfoDTO>(res.Item1);
                    list.RecordCount = res.Item2;
                    list.PageCount = res.Item3;
                    list.IsHaveNext = res.Item4;
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                strError = string.Format("GetGroupOne Exception:{0}", ex.ToString());
            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return list;
        }

        /// <summary>
        /// 根据父ID获取群组信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<List<GroupInfoDTO>> GetGroupByPID(GroupQuery query)
        {
            List<GroupInfoDTO> list = new List<GroupInfoDTO>();
            string strError = "";
            LogEntity.Module = "XF.Meeting.Service.MeetingService.GetGroupByPID";
            LogEntity.OperateObject = "GetGroupByPID";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {
                var res = await dal.GetGroupByPID(query, out strError);

                if (strError == "")
                {
                    list = TableToList.ToList<GroupInfoDTO>(res);
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                strError = string.Format("GetGroupByPID Exception:{0}", ex.ToString());
            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return list;
        }

        /// <summary>
        /// 获取群组信息   Mobile
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageListMobile<GroupInfoDTO>> GetGroupForMobile(GroupQuery query)
        {

            PageListMobile<GroupInfoDTO> list = new PageListMobile<GroupInfoDTO>();
            List<GroupInfoDTO> mobileList = new List<GroupInfoDTO>();
            List<GroupInfoDTO> newList = new List<GroupInfoDTO>();
            List<GroupInfoDTO> infoList = new List<GroupInfoDTO>();
            List<GroupInfoDTO> listKey = new List<GroupInfoDTO>();
            string strError = "";
            LogEntity.Module = "XF.Meeting.Service.MeetingService.GetRegionalForMobile";
            LogEntity.OperateObject = "GetRegionalForMobile";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {
                DataTable res = new DataTable();

                query.ParentID = 1;
                res = await dal.GetGroupByPID(query, out strError);
                if (strError == "")
                {

                    mobileList = TableToList.ToList<GroupInfoDTO>(res);
                    newList = await GetNewList(mobileList);
                    newList = newList.DistinctBy(I => I.GroupID).ToList();  //去除重复数据
                    if(query.Key!=""&&query.Key!=null)
                    {
                        newList = newList.Where(x => x.GroupName.Contains(query.Key)).ToList(); //根据关键字过滤
                    }

                    if (newList.Count > query.pageIndex * query.pageSize)
                    {
                        list.IsHaveNext = false;
                    }
                    else
                    {
                        list.IsHaveNext = true;
                    }
                    for (int i = (query.pageIndex - 1) * query.pageSize; i < query.pageIndex * query.pageSize && i < newList.Count; i++)//逻辑分页
                    {

                        infoList.Add(newList[i]);

                    }
                    list.List = infoList;
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                strError = string.Format("GetRegionalForMobile Exception:{0}", ex.ToString());
            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return list;
        }

        /// <summary>
        /// 递归拼接群组  格式：   西安·高新·软件园·汉韵阁    （有重复数据，需要去重）
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<List<GroupInfoDTO>> GetNewList(List<GroupInfoDTO> list)
        {
            List<GroupInfoDTO> newList = new List<GroupInfoDTO>();
            List<GroupInfoDTO> newList1 = new List<GroupInfoDTO>();
            foreach (var item in list)
            {
                GroupInfoDTO info = new GroupInfoDTO();
                info.GroupID = item.GroupID;
                info.GroupName = item.GroupName;
                newList.Add(info);
                newList1 = await GetGroupByPID(new GroupQuery()//根据父ID获取子区域
                {
                    ParentID = item.GroupID
                });
                foreach (var b in newList1)//循环拼接
                {
                    GroupInfoDTO info1 = new GroupInfoDTO();
                    info1.GroupID = b.GroupID;
                    info1.GroupName = item.GroupName + "·" + b.GroupName;
                    newList.Add(info1);
                }
                var c = await GetNewList(newList1);//递归
                foreach (var d in c)
                {
                    GroupInfoDTO info2 = new GroupInfoDTO();
                    info2.GroupID = d.GroupID;
                    info2.GroupName = item.GroupName + "·" + d.GroupName;//再次循环拼接
                    newList.Add(info2);
                }
            }
            return newList;
        }

        /// <summary>
        /// 根据群组ID获取用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageList<UserInfoForSearch>> GetUserListByGroupIdAndKey(GroupQuery query)
        {

            PageList<UserInfoForSearch> list = new PageList<UserInfoForSearch>();
            
            
            string strError = "";
            LogEntity.Module = "XF.Meeting.Service.MeetingService.GetUserListByGroupIdAndKey";
            LogEntity.OperateObject = "GetUserListByGroupIdAndKey";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {
                

                
                var res = await dal.GetUserListByGroupIdAndKey(query, out strError);
                if (strError == "")
                {
                    list.List = TableToList.ToList<UserInfoForSearch>(res.Item1);
                    list.RecordCount = res.Item2;
                    list.PageCount = res.Item3;
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                strError = string.Format("GetUserListByGroupIdAndKey Exception:{0}", ex.ToString());
            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return list;
        }

        /// <summary>
        /// 根据群组ID获取用户列表（预约编辑回显）
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PageList<UserInfoForSearch>> GetUserListByGroupIdForUpdate(GroupQuery query)
        {

            PageList<UserInfoForSearch> list = new PageList<UserInfoForSearch>();
            List<UserInfoForSearch> userlist = new List<UserInfoForSearch>();

            string strError = "";
            LogEntity.Module = "XF.Meeting.Service.MeetingService.GetUserListByGroupIdAndKey";
            LogEntity.OperateObject = "GetUserListByGroupIdAndKey";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {



                var res = await dal.GetUserListByGroupIdAndKey(query, out strError);
                if (strError == "")
                {
                    userlist = TableToList.ToList<UserInfoForSearch>(res.Item1);
                    string[] UserIDs = query.UserIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < UserIDs.Length; i++)
                    {
                        foreach (var item in userlist)
                        {
                            if (UserIDs[i] == item.ID.ToString())
                            {
                                item.IsChoice = true;
                            }
                        }
                    }
                    list.RecordCount = res.Item2;
                    list.PageCount = res.Item3;
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                strError = string.Format("GetUserListByGroupIdAndKey Exception:{0}", ex.ToString());
            }
            LogEntity.ErrorDescription = strError;
            RecordLog();
            return list;
        }

        /// <summary>
        /// 系统日志
        /// </summary>
        private void RecordLog()
        {
            LogEntity.Operator = Operator;
            LogEntity.OperateIP = OperaIP;
            ULogWork.CLogToDataBase.RecordOperateLog(LogEntity);
        }

        public Task<List<GroupInfoDTO>> GetGroupList()
        {
            throw new NotImplementedException();
        }

        public Task<PageList<GroupUserInfoDTO>> GetUserListByGroupId(UserQuery obj)
        {
            throw new NotImplementedException();
        }

        public Task<(bool, string)> Insert(GroupInfo obj)
        {
            throw new NotImplementedException();
        }

        public Task<(bool, string)> Delete(GroupInfo obj)
        {
            throw new NotImplementedException();
        }

        public Task<(bool, string)> AddUser(GroupInfo obj)
        {
            throw new NotImplementedException();
        }

        public Task<(bool, string)> RemoveUser(GroupInfo obj)
        {
            throw new NotImplementedException();
        }
    }
}
